#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

namespace network
{
    const static int defaultsockfd = -1;
    const static int defaultbacklog = 5;
    enum
    {
        Sock_erro = 1,
        Bind_erro,
        Listen_erro
    };

    // 模板方法
    /*抽象类接口，重写*/
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void CreateSocketOrDie() = 0;//创建网络文件描述符sockfd
        virtual void BindSocket(uint16_t port) = 0;//绑定到内核数据结构
        virtual void ListenSocket(int backlog) = 0;//服务器监听客户端的连接
        virtual Socket *AcceptConnection(std::string& peerip, uint16_t &peerport) = 0;//服务器接收客户端创建链接
        virtual bool ConnectSever(std::string &severIp, uint16_t severport) = 0;//客户端向服务器发送链接
        virtual int GetSockfd() = 0;//获得sockfd
        virtual void SetSockfd(int sockfd) = 0;
        virtual void CloseSockfd() = 0;
        virtual bool Recv(std::string *buffer,int size) = 0;
        virtual void Send(std::string &sendstring) = 0;
        virtual void ReUserAddr() = 0;

    public:
        void BuildListenSocketMethod(uint16_t port, int backlog = defaultbacklog)
        {
            CreateSocketOrDie();
            ReUserAddr();
            BindSocket(port);
            ListenSocket(backlog);
        }
        bool BuildClientSocketMethod(std::string severIP, uint16_t severport)
        {
            CreateSocketOrDie();
            return ConnectSever(severIP, severport);
        }
        void BuildNormalSocketMethod(int sockfd)
        {
            SetSockfd(sockfd);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = defaultsockfd) : _sockfd(sockfd)
        {
        }
        virtual ~TcpSocket() {}
        virtual void CreateSocketOrDie()
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
                exit(Sock_erro);
        }
        virtual void BindSocket(uint16_t port)
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(port);
            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
                exit(Bind_erro);
        }
        virtual void ListenSocket(int backlog)
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
                exit(Listen_erro);
        }
        virtual Socket *AcceptConnection(std::string &peerip, uint16_t& peerport)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (newsockfd < 0)
                exit(Listen_erro);
            peerport = ntohs(peer.sin_port);
            peerip = inet_ntoa(peer.sin_addr);
            Socket *s = new TcpSocket(newsockfd);
            return s;
        }
        virtual bool ConnectSever(std::string &severIp, uint16_t severport)
        {
            struct sockaddr_in sever;
            memset(&sever, 0, sizeof(sever));
            sever.sin_family = AF_INET;
            sever.sin_addr.s_addr = inet_addr(severIp.c_str());
            sever.sin_port = htons(severport);
            int n = ::connect(_sockfd, (struct sockaddr *)&sever, sizeof(sever));
            if (n == 0)
                return true;
            return false;
        }
        virtual int GetSockfd()
        {
            return _sockfd;
        }
        virtual void SetSockfd(int sockfd)
        {
            _sockfd = sockfd;
        }
        virtual void CloseSockfd()
        {
            if (_sockfd > defaultsockfd)
            {
                ::close(_sockfd);
            }
        }
        virtual bool Recv(std::string *buffer,int size)
        {
            char inbuffer[size];
            ssize_t n = recv(_sockfd,inbuffer,size - 1,0);
            if(n > 0)
            {
                inbuffer[n] = 0;
                *buffer += inbuffer;
                //std::cout << "recv success"<<std::endl;
                return true;
            }
            else if(n == 0)
            {
                return false;
            }
            else
            {
                return false;
            }
        }
        virtual void Send(std::string &sendstring)
        {
            send(_sockfd,sendstring.c_str(),sendstring.size(),0);
        }
        virtual void ReUserAddr()
        {
            int opt = 1;
            setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        }
    public:
        void BuildListenSocket(uint16_t port, int backlog)
        {
            CreateSocketOrDie();
            BindSocket(port);
            ListenSocket(backlog);
        }
        void BuildClientSocket(std::string &severIP, uint16_t severport)
        {
            CreateSocketOrDie();
            ConnectSever(severIP, severport);
        }
        void BuildNormalSocket(int sockfd)
        {
            SetSockfd(sockfd);
        }

    private:
        int _sockfd;
    };
}